package com.mengjiahui.auduoplayer.fragment;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.mengjiahui.auduoplayer.R;
import com.mengjiahui.auduoplayer.activity.MusicRankInfoActivity;
import com.mengjiahui.auduoplayer.adapter.OnlineMusicAdapter;
import com.mengjiahui.auduoplayer.bean.Music;
import com.mengjiahui.auduoplayer.bean.MusicRank;
import com.mengjiahui.auduoplayer.util.SpacesItemDecoration;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

/**
 * @author Meng
 * @data 2020/5/9
 */
public class OnlineMusicFragment extends Fragment {
    private RecyclerView recyclerView;
    private int[] typeIds=new int[]{
            1,2,11,21,22,23,24,25
    };
    private  String RANK_BASE_URL="https://tingapi.ting.baidu.com/v1/restserver/ting?format=json&method=baidu.ting.billboard.billList&type=#&size=10&offset=0";
    private String MUSIC_BASE_URL="https://tingapi.ting.baidu.com/v1/restserver/ting?format=json&calback=&method=baidu.ting.song.play&songid=";;
    private View view;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_online_music, container, false);
        recyclerView = view.findViewById(R.id.recyclerView);
        MusicRankAsyncTask musicRankAsyncTask=new MusicRankAsyncTask();
        musicRankAsyncTask.execute();
        return view;
    }


    class MusicRankAsyncTask extends AsyncTask<String, Integer, Void> {
        private List<MusicRank> musicRankList=new ArrayList<>();

        @Override
        protected Void doInBackground(String... strings) {
            for(int i=0;i<typeIds.length;i++){
                try {
                    URL url = new URL(RANK_BASE_URL.replace("#", String.valueOf(typeIds[i])));
                    HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
                        public boolean verify(String string, SSLSession ssls) {
                            return true;
                        }
                    });
                    JSONObject jsonObject =getJson(url);
                    MusicRank musicRank=new MusicRank();
                    JSONArray songList=jsonObject.getJSONArray("song_list");
                    List<Music> musicList=new ArrayList<>();
                    for(int j=0;j<songList.length();j++){
                        JSONObject song= (JSONObject) songList.get(j);
                        Music music=new Music();
                        music.setMusicName(song.getString("title"));
                        music.setAuthor(song.getString("author"));
                        music.setPath(song.getString("pic_small"));
                        music.setMusicId(song.getInt("song_id"));
                        URL musicUrl = new URL(MUSIC_BASE_URL+music.getMusicId());
                        JSONObject musicJsonObject=getJson(musicUrl);
                        music.setFileLink(musicJsonObject.getJSONObject("bitrate").getString("file_link"));
                        musicList.add(music);
                    }
                    JSONObject billBoard=jsonObject.getJSONObject("billboard");
                    musicRank.setImg(billBoard.getString("pic_s192"));
                    musicRank.setRankName(billBoard.getString("name"));
                    musicRank.setUpdateDate(billBoard.getString("update_date"));
                    musicRank.setComment(billBoard.getString("comment"));
                    musicRank.setMusicList(musicList);
                    musicRankList.add(musicRank);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            return null;
        }

        private JSONObject getJson(URL url) throws IOException, JSONException {
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            //从连接中获得InputStream
            InputStream inputStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            //转换成字符串
            String result = "";
            StringBuilder builder = new StringBuilder();
            while((result = reader.readLine())!= null){
                builder.append(result);
            }
            String text = builder.toString();
            JSONObject jsonObject = new JSONObject(text);
            return  jsonObject;
        }


        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            OnlineMusicAdapter onlineMusicAdapter=new OnlineMusicAdapter(musicRankList);
            onlineMusicAdapter.setListener(musicRank->{
                Intent intent=new Intent(getActivity(), MusicRankInfoActivity.class);
                intent.putExtra("musicRank",musicRank);
                startActivity(intent);
            });
            recyclerView.setAdapter(onlineMusicAdapter);
            LinearLayoutManager linearLayoutManager=new LinearLayoutManager(null);
            recyclerView.setLayoutManager(linearLayoutManager);
        }
    }


}